<template>
  <div>

    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="1">作业管理</el-menu-item>
      <el-menu-item index="2"@click="jump">文件管理</el-menu-item>
    </el-menu>
    <div class="line"></div>


    <el-card style="padding: 10px">

      <el-form :model="queryParams">
        <el-input
          style="width: 240px"
          v-model="queryParams.teacherId"
          placeholder="请输入教师id"
        />
        <el-button >查   询</el-button>

      </el-form>


      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        >
        <el-table-column label="id" align="center" prop="id" width="150px"/>
        <el-table-column prop="title" label="题目">
          <template slot-scope="scope">
            <div v-html="scope.row.title"></div>
          </template>
        </el-table-column>
        <!--        <el-table-column label="题目" align="center" prop="title" />-->
        <el-table-column label="分值" align="center" prop="score" />
<!--        <el-table-column label="得分" align="center" prop="score" />-->
<!--          <el-table-column label="操作" width="200px">-->
<!--          <template slot-scope="scope">-->
<!--            <el-button type="primary" size="mini" @click="QuestionPut(scope.row)">提 交</el-button>-->
<!--            <el-upload-->
<!--              multiple-->
<!--              :action="uploadFileUrl"-->
<!--              :before-upload="handleBeforeUpload"-->
<!--              :file-list="fileList"-->
<!--              :limit="limit"-->
<!--              :on-error="handleUploadError"-->
<!--              :on-exceed="handleExceed"-->
<!--              :on-success="handleUploadSuccess"-->
<!--              :show-file-list="false"-->
<!--              :headers="headers"-->
<!--              class="upload-file-uploader"-->
<!--              ref="upload"-->
<!--            >-->
<!--              &lt;!&ndash; 上传按钮 &ndash;&gt;-->
<!--              <el-button size="mini" type="primary" @click="uploadId(scope.row)">提交</el-button>-->
<!--              &lt;!&ndash; 上传提示 &ndash;&gt;-->
<!--&lt;!&ndash;              v-if="flag1 != 0 ? true:false"&ndash;&gt;-->
<!--              <div class="el-upload__tip" slot="tip" v-if="showTip">-->
<!--                请上传-->
<!--                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>-->
<!--                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>-->
<!--                的文件-->
<!--              </div>-->
<!--            </el-upload>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="得分" align="center" prop="score" />-->

        <el-table-column  width="200px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="QuestionDetail(scope.row)">查  看</el-button>

          </template>
        </el-table-column>
      </el-table>

    </el-card>
    <el-dialog title="查看成绩" :visible.sync="dialogFormVisible" width="50%" size="small">
<!--      <el-form label-width="120px">-->
<!--        <el-form-item label="成绩">-->
<!--          <el-input v-model="form5.score" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="教师评语">-->
<!--          <el-input v-model="form5.comments" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
<!--      </el-form>-->

      <el-table
        ref="multipleTable"
        :data="tableData1"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column label="id" align="center" prop="id" width="150px" v-if="false"/>
        <!--        <el-table-column label="进行中"></el-table-column>-->
        <el-table-column label="作业名" align="center" prop="filename">
          <template slot-scope="scope">
            <a @click="preView(scope.row.filename)" target="_blank" class="buttonText" style="color: #00afff;text-decoration:underline">{{scope.row.filename}}</a>
          </template>
        </el-table-column>
<!--        <el-table-column label="作业名" align="center" prop="filename" />-->
        <el-table-column label="成绩" align="center" prop="score"/>
        <el-table-column label="评语" align="center" prop="comments" />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
<!--        <el-button type="primary" @click="edit">确 定</el-button>-->
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import { queryQuestionList} from "@/api/teacher/detail/course/detail";
  import { getUserProfile } from "@/api/system/user";
  import { queryProblemByTopicId,eidtProblem,queryProblemById,DeleteProblem,queryByTopicId} from "@/api/teacher/addTopic";
  import { queryCourseList,saveTopic,queryCourseListByCreator,queryCourseListByTitle,saveProblem,queryByTopic} from "@/api/teacher/detail/course/QuestionBank";
  import {getToken} from "@/utils/auth";
  import {checkmyself} from "@/api/student/topic"
  import {updatefile,queryByFileName,checkedd} from "@/api/student/TopicDetail"
  import {queryByStudent} from "@/api/student/TopicDetail2"
  export default {
    name: "TopicDetail2",
    props: {
      // 值
      value: [String, Object, Array],
      // 数量限制
      limit: {
        type: Number,
        default: 100,
      },
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 5,
      },
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
        type: Array,
        default: () => ["doc", "docx"],
      },
      // 是否显示提示
      isShowTip: {
        type: Boolean,
        default: true
      }
    },
    created() {
      this.getUser();
    },
    data(){
      return {
        flag1:false,
        visible: false,
        dialogFormVisible:false,
        form:{},
        form1:{},
        form2:{
          id:null,
          userId:null,
          userid:null,
          subtopid:null,
          problemid:null,
          classid:null,
          fileName:null
        },
        form3:{
          userid:undefined,
          problemid:undefined
        },
        form4:{
          userid:undefined,
          problemid:undefined
        },
        form5:{},
        activeIndex: '1',
        problemid:null,
        activeIndex2: '1',
        queryParams: {
          pageNum: undefined,
          pageSize: undefined,
          teacherId: null,
        },
        user: {},
        tableData: [],
        tableData1: [],
        data1:null,

        number: 0,
        uploadList: [],
        baseUrl: process.env.VUE_APP_BASE_API,
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/simhash/topFile/check2", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        fileList: [],
      }
    },
    watch: {
      value: {
        handler(val) {
          if (val) {
            let temp = 1;
            // 首先将值转为数组
            const list = Array.isArray(val) ? val : this.value.split(',');
            // 然后将数组转为对象数组
            this.fileList = list.map(item => {
              if (typeof item === "string") {
                item = {name: item, url: item};
              }
              item.uid = item.uid || new Date().getTime() + temp++;
              return item;
            });
          } else {
            this.fileList = [];
            return [];
          }
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      // 是否显示提示
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize);
      },
    },
    methods: {
      getUser() {
        this.id = this.$route.query.id//创建作业后传过来title
        this.form2.classid = this.$route.query.classId
          queryProblemByTopicId(this.id).then(response => {
            this.tableData = response
          })
        // this.form2.classid = this.classid
        getUserProfile().then(response => {
          this.form3.userid = response.data.userName;
          this.form4.userid = response.data.userName;
        })
      },
      QuestionPut(row){

      },
      QuestionDetail(row){
        this.dialogFormVisible = true,
        this.form4.problemid = row.id
        // console.log(this.form4)
        queryByStudent(this.form4).then(response =>{
          console.log(response)
          // this.tableData2 = response
          // console.log(response)
          this.form5 = response
          this.tableData1 = response
        })
      },
      handleSelect(key, keyPath) {
        console.log(key, keyPath);
      },

      jump(){
        this.$router.push('teacher/FileBank')
      },
      // 上传前校检格式和大小
      handleBeforeUpload(file) {
        this.form2.fileName = file.name
        // 校检文件类型
        if (this.fileType) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          const isTypeOk = this.fileType.some((type) => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
          if (!isTypeOk) {
            this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
            return false;
          }
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        return true;
      },
      // 文件个数超出
      handleExceed() {
        this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
      },
      // 上传失败
      handleUploadError(err) {
        this.$modal.msgError("上传图片失败，请重试");
        this.$modal.closeLoading()
      },
      // 上传成功回调
      uploadId(row){

        this.form2.problemid = row.id

         console.log(this.problemId)
        // getUserProfile().then(response => {
        //   this.form3.userid = response.data.userName;
        // })
        this.form3.problemid  = row.id

         checkmyself(this.form3).then(response =>{

           if(response.msg ==="已提交"){
             alert("已提交")
            return false;
           }

         })
      },
      handleUploadSuccess(res) {
        this.uploadList.push({name: res.fileName, url: res.fileName});
        // console.log(name)
        // console.log(res.fileName)
        if (this.uploadList.length === this.number) {
          this.fileList = this.fileList.concat(this.uploadList);
          this.uploadList = [];
          this.number = 0;
          this.$emit("input", this.listToString(this.fileList));
          this.$modal.closeLoading();
          // console.log(res)
          const temm = res.msg
          // console.log(scope.row)
          // console.log(scope.row.id)
          getUserProfile().then(response => {
            this.form2.userid = response.data.userName;
            // console.log(this.form2.userId)
            this.form2.subtopid = this.$route.query.id//创建作业后传过来title
            // console.log(this.form2.subTopId)
            // console.log(this.form2.problemId)
            // console.log("form2")
            // console.log(this.form2)
          })
//           console.log("文件名")
// console.log(this.form2.fileName)

// 这里是修改三个一
          if (res.code === '20220') {
//             queryByFileName(this.form2.fileName).then(response =>{
//               // console.log("response.id")
//               // console.log(response)
//               this.form2.id = response
//               // console.log(123)
//               // console.log(this.form2)
//
//               updatefile(this.form2).then(response =>{
//                 console.log(response)
//                 this.$message.success("修改成功")
//               })
//             })
//
//
//
            this.$message.success(temm)
          }
//           }else {
//             this.$message.error(temm)
//           }
        }
      },
      // 删除文件
      handleDelete(index) {
        this.fileList.splice(index, 1);
        this.$emit("input", this.listToString(this.fileList));
      },
      // 获取文件名称
      getFileName(name) {
        if (name.lastIndexOf("/") > -1) {
          return name.slice(name.lastIndexOf("/") + 1);
        } else {
          return "";
        }
      },
      // 对象转成指定字符串分隔
      listToString(list, separator) {
        let strs = "";
        separator = separator || ",";
        for (let i in list) {
          strs += list[i].url + separator;
        }
        return strs != '' ? strs.substr(0, strs.length - 1) : '';
      }
    }
  }
</script>

<style scoped lang="scss">
  .upload-file-uploader {
    margin-bottom: 5px;
  }

  .upload-file-list .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 10px;
    position: relative;
  }

  .upload-file-list .ele-upload-list__item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
  }

  .ele-upload-list__item-content-action .el-link {
    margin-right: 10px;
  }
</style>
